<?php

/**
 * cookie管理控制类
 * 
 * @desc 对cookie进行存储、读取、更新、删除、清空操作 
 * @author keluo <pycorvn@yeah.net>
 */
class SCCookie {
		
	/**
	 * 设置cookie
	 * @param string $name cookie名
	 * @param string or array
	 */
	public static function set($name, $value, $expire = 3600, $path = '/', $domain = '') {
		$value = is_array($value) ? json_encode($value) : $value;
		setcookie(self::rename($name), $value, time() + $expire, $path, $domain);
	}

	/**
	 * cookie重命名，防止与其他cookie值发生冲突覆盖情况
	 * @param string $name
	 */
	protected static function rename($name) {
		return substr(md5($name), 0, 8).'_'.$name;
	}
	
	/**
	 * 获取cookie值
	 * @param string $name
	 * @return string or array or false
	 */
	public static function get($name) {
		$name = self::rename($name);
		if(isset($_COOKIE[$name]) && strlen($_COOKIE[$name]) != 0) {
			$tmp = json_decode($_COOKIE[$name]);
			if(is_array($tmp)) {
				return $tmp;
			}
			return $_COOKIE[$name];
		} else {
			return false;
		}
	}
	
	/**
	 * 删除cookie
	 * @param string $name
	 */
	public static function delete($name, $path = '/') {
		setcookie(self::rename($name), '', time() - 3600*24*30, '/');
	}
	
	/**
	 * 清空cookie
	 */
	public static function clear() {
		if(!empty($_COOKIE) && count($_COOKIE) != 0) {
			foreach($_COOKIE as $name=>$value) {
				setcookie($name, '', time() - 3600*24*30, '/');
			}
		}
	}
}